package com.borya;

import java.awt.Image;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.borya.util.DateUtils;
import com.borya.util.FileUtils;
import com.borya.util.ImageUtils;

public class ProcessSignPic {

	public static void main(String[] args)throws Exception {
		final String dirPath = "/root/newdir/sign_img/sign/";
		final String outFilePath = "/root/";
		
		File dir = new File(dirPath);
		File[] files = dir.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				if(name == null){
					return false;
				}
				
//				if(name.trim().length() != "17092510288_170809180730784.jpg".length()){
//					return false;
//				}
				
				if(name.trim().contains("_merge")){
					return false;
				}
				
//				int index = name.trim().indexOf("_");
//				if(index != 11){
//					return false;
//				}
				
				return true;
			}
		});
		if(files == null || files.length == 0){
			return;
		}
		// 文件排序
		List<File> listFiles = Arrays.asList(files);
		Collections.sort(listFiles, new Comparator<File>() {
			@Override
			public int compare(File f1, File f2) {
				String array1[] = f1.getName().split("_");
				String array2[] = f2.getName().split("_");
				if(array1[0].equals(array2[0])){
					return array1[1].compareTo(array2[1]);
				}
				
				return array1[0].compareTo(array2[0]);
			}
		});
		
		Connection conn = getConnection();
		if(conn == null){
			System.out.println("DB connection excepton.");
			return ;
		}
		
		//如果文件存在，则追加内容；如果文件不存在，则创建文件
		File f = new File(outFilePath);
		if(f.exists()){
			f.delete();
		}
		
		f.mkdirs();
		
		File fileOut = new File(outFilePath+"merchant_out.txt");
		fileOut.createNewFile();
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut, true)));
		final String destDir = dirPath;
		for(File signImgFile : listFiles){
			final String phone = signImgFile.getName().substring(0,signImgFile.getName().indexOf("_"));
			Merchant merchant = getSignInfo(conn,phone);
			if(merchant == null){
				System.out.println("DB not found dealerId,phone"+phone);
				continue;
			}
			
			try(InputStream is = ProcessSignPic.class.getResourceAsStream("/resources/代理商户合作协议.png");) {
				String fileNameMerge = signImgFile.getName().substring(0,signImgFile.getName().indexOf("."))+"_merge.jpg";
				final String signImgCopyPath = destDir + fileNameMerge+ "_copy.jpg";
				File signImgCopyFile = new File(signImgCopyPath);
				// 文件拷贝
				FileUtils.copyFile(signImgFile, signImgCopyFile);
				Image src1 = javax.imageio.ImageIO.read(is);
				//获取图片的宽度/高度  
				final int width1 = src1.getWidth(null);
				Image src3 = javax.imageio.ImageIO.read(signImgCopyFile);
				final int width2 = src3.getWidth(null);
				final int height2 = src3.getHeight(null);
				if (width1 != width2) {
					//等比缩放
					ImageUtils.narrowImage(signImgCopyPath, width1,
							(int) ((double) width1 / width2 * height2));
				} else {
					// Ignore
				}
				//final long curTime = System.currentTimeMillis();
				//yyyy-MM-dd HH:mm:ss
				final String date = (merchant.getSignTime() > 0) ? DateUtils
						.format(merchant.getSignTime(),"yyyy-MM-dd HH:mm:ss") : "";
				String deviceId = "";
				if (merchant.getDeviceId() != null
						&& merchant.getDeviceId().trim().length() > 0) {
					deviceId = merchant.getDeviceId().trim();
				}
				List<String> list = new ArrayList<String>();
				list.add("签约时间:" + date);
				list.add("签约人:" + phone);
				list.add("设备ID:" + deviceId);//YT620175200871
				// destDir + fileNameMerge +"_copy.png";
				ImageUtils.createImg(destDir, fileNameMerge + "_water.jpg",
						list, width1);
				File file2 = new File(destDir + fileNameMerge + "_water.jpg");
				ImageUtils.mergeImageVertically(src1, file2, destDir + "/"+ fileNameMerge + "_2.jpg");
				File fileTmpe2 = new File(destDir + "/" + fileNameMerge
						+ "_2.jpg");
				Image src2_ = javax.imageio.ImageIO.read(fileTmpe2);
				// 图片合并
				Image src3_ = javax.imageio.ImageIO.read(signImgCopyFile);
				ImageUtils.mergeImageVertically(src2_, src3_, destDir + "/"+ fileNameMerge);
				signImgCopyFile.delete();
				fileTmpe2.delete();
				file2.delete();
				
				String str = "update tb_merchant set sign_merge_picture='"+fileNameMerge+"' "
						+"where dealer_id='"+merchant.getDealerId()+"';";
				System.out.println(str);
				
				out.write(str+"\r\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		out.close();
	}
	
	private static Connection getConnection() {
		String url = "jdbc:mysql://192.168.10.109:3306/cardmen1?characterEncoding=UTF-8";
		String user = "root";
		String password = "123";
		try{
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection(url, user, password);
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	private static Merchant getSignInfo(Connection conn,String phone) {
		PreparedStatement pst = null;
		ResultSet rs = null;
		try{
			String sql = "select dealer_id,devMac,sign_time from tb_merchant"
					+" where dealer_id=(select dealer_id from tb_user_client where phone='"+phone+"' limit 1)";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			if(rs != null && rs.next()){
				Merchant m = new Merchant();
				m.setDealerId(rs.getString("dealer_id"));
				m.setDeviceId(rs.getString("devMac"));
				m.setSignTime(rs.getLong("sign_time"));
				return m;
			}
			
			rs.close();
			pst.close();
			sql = "select dealer_id,devMac,sign_time from tb_merchant"
					+" where dealer_id=(select dealer_id from tb_user_client where userid='"+phone+"' limit 1)";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			if(rs != null && rs.next()){
				Merchant m = new Merchant();
				m.setDealerId(rs.getString("dealer_id"));
				m.setDeviceId(rs.getString("devMac"));
				m.setSignTime(rs.getLong("sign_time"));
				return m;
			}
			
			return null;
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
		finally{
			if(pst != null){
				try {
					pst.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			if(rs != null){
				try {
					rs.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}

	}
	
	static class Merchant{
		private String dealerId;
		private long signTime;
		private String deviceId;
		public String getDealerId() {
			return dealerId;
		}
		public void setDealerId(String dealerId) {
			this.dealerId = dealerId;
		}
		public long getSignTime() {
			return signTime;
		}
		public void setSignTime(long signTime) {
			this.signTime = signTime;
		}
		public String getDeviceId() {
			return deviceId;
		}
		public void setDeviceId(String deviceId) {
			this.deviceId = deviceId;
		}
		@Override
		public String toString() {
			return "Merchant [dealerId=" + dealerId + ", signTime=" + signTime + ", deviceId=" + deviceId + "]";
		}
	}
}
